package com.tanhua.server.service;

import com.tanhua.commons.exception.TanHuaException;
import com.tanhua.db.Question;
import com.tanhua.db.Settings;
import com.tanhua.db.User;
<<<<<<< HEAD
=======
import com.tanhua.db.UserInfo;
>>>>>>> acc7004 (第4天到第8天)
import com.tanhua.dubbo.api.PageResultApi;
import com.tanhua.dubbo.api.QuestionApi;
import com.tanhua.dubbo.api.SettingsApi;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.vo.ErrorResult;
import com.tanhua.vo.PageResult;
import com.tanhua.vo.SettingsVo;
import com.tanhua.vo.UserInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
<<<<<<< HEAD
=======
import org.apache.dubbo.common.utils.CollectionUtils;
>>>>>>> acc7004 (第4天到第8天)
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

<<<<<<< HEAD
=======
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

>>>>>>> acc7004 (第4天到第8天)
/**
 * @version 1.0
 * @author： xtr
 * @date： 2021-03-07 19:03
 */
@Service
@Slf4j
public class SettingsService {

    @Reference
    private SettingsApi settingsApi;

    @Reference
    private QuestionApi questionApi;

    @Reference
    private PageResultApi pageResultApi;

    @Reference
    private UserApi userApi;

    @Value("${tanhua.redisValidateCodeKeyPrefix}")
    private String redisValidateCodeKeyPrefix;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 用户通用设置 - 读取
     * 查询用户的设置信息
     * @return
     */
    public SettingsVo getSettings() {

        //获取当前登录用户id
        User user = UserHolder.getUser();
        //获取陌生人问题
        Question question = questionApi.findByUserId(user.getId());
        //获取settings设置
        Settings settings = settingsApi.getSettingsById(user.getId());
        //构建settingVo
        SettingsVo settingsVo = new SettingsVo();
        if (question!=null){
            settingsVo.setStrangerQuestion(question.getTxt());
        }
        //设置陌生人问题
        if (settings!=null){
            BeanUtils.copyProperties(settings,settingsVo);
        }
        //设置手机号
        settingsVo.setPhone(user.getMobile());
        log.info("settings设置=========== {}",settingsVo);
        return settingsVo;
    }

    /**
     * 更新settings设置信息
     * @param vo
     */
    public void updateSettings(SettingsVo vo) {
        //获取用户id
        Long userId = UserHolder.getUserId();
        //查询settings是否存在该用户
        Settings settingsById = settingsApi.getSettingsById(userId);
        //判空，空存，不空更新
        if (null!=settingsById){
            //直接复制到pojo对象,忽略id，vo是前端传过来的，id没有值，所以不能被覆盖
            BeanUtils.copyProperties(vo,settingsById,"id");
            settingsApi.updateSettings(settingsById);
        }else {
            //没有，则保存
            //设置属性
            settingsById = new Settings();
            //复制属性
            BeanUtils.copyProperties(vo,settingsById);
            //设置用户id
            settingsById.setUserId(userId);
            settingsApi.saveSettings(settingsById);
        }
    }

    /**
     * 设置陌生人问题 - 保存
     * @param question
     */
    public void updateQuestion(String question) {
        //获取用户信息
        User user = UserHolder.getUser();
        //查询question表是否存在该用户
        Question questionApiByUserId = questionApi.findByUserId(user.getId());
        if (questionApiByUserId!=null){
            //不为空，则更新
            questionApiByUserId.setTxt(question);
            questionApi.update(questionApiByUserId);
            log.info("更新的问题========={}",questionApiByUserId);
        }else {
            //为空则新增
            questionApiByUserId = new Question();
            questionApiByUserId.setUserId(user.getId());
            questionApiByUserId.setTxt(question);
            questionApi.save(questionApiByUserId);
            log.info("保存的问题========={}",questionApiByUserId);
        }
    }

    /**
     * 黑名单 - 翻页列表
     * 分页查询黑名单
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult<UserInfoVo> findBlackList(long page, long pagesize) {
        //获取用户ID
        Long userId = UserHolder.getUserId();
        PageResult pageResult = pageResultApi.findBlackList(page,pagesize,userId);
//        List<UserInfo> items = (List<UserInfo>)pageResult.getItems();
//        if (CollectionUtils.isNotEmpty(items)){
////            List<UserInfoVo> list = items.stream().map(userInfo -> {
////                UserInfoVo userInfoVo = new UserInfoVo();
////                BeanUtils.copyProperties(userInfo, userInfoVo);
////                userInfoVo.setAge(userInfo.getAge().toString());
////                log.info("黑名单=============={}",userInfoVo);
////                return userInfoVo;
////            }).collect(Collectors.toList());
////            pageResult.setItems(list);
//            // 接收的集合，转在的目标集合
//            List<UserInfoVo> list = new ArrayList<UserInfoVo>();
//            // 遍历查询到的结果集
//            for (UserInfo item : items) {
//                // 创建 vo对象
//                UserInfoVo vo = new UserInfoVo();
//                // 复制属性值
//                BeanUtils.copyProperties(item, vo);
//                vo.setAge(item.getAge().toString());
//                // 添加到新集合里
//                list.add(vo);
//                log.info("黑名单=============={}",vo);
//            }
//            pageResult.setItems(list);
//        }
        return pageResult;
    }

    /**
     * 修改手机号,校验验证码
     * @param verificationCode
     * @return
     */
    public boolean checkVerificationCode(String verificationCode){
        User user = UserHolder.getUser();
        String key = redisValidateCodeKeyPrefix + user.getMobile();
        String codeInRedis = redisTemplate.opsForValue().get(key);
//        try {
//            codeInRedis = new String(codeInRedis.getBytes("ISO-8859-1"),"UTF-8");
//            verificationCode = new String(verificationCode.getBytes("ISO-8859-1"),"UTF-8");
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
        log.debug("==========修改手机号 校验 验证码:{},{},{}",user.getMobile(),codeInRedis,verificationCode);
        if(StringUtils.isEmpty(codeInRedis)){
            throw new TanHuaException(ErrorResult.loginError());
        }
        if(!(codeInRedis.equals(verificationCode))){
            return false;
        }
        redisTemplate.delete(key);
        return true;
    }

    /**
     * 保存修改的手机号
     * @param phone
     */
    public void savePhone(String phone,String token) {
        User user = UserHolder.getUser();
        String key ="TOKEN_"+token;
        log.info("key============={}"+key);
        Long userId = user.getId();
        userApi.update(phone,userId);
        redisTemplate.delete(key);
    }

    /**
     * 删除黑名单
     * @param uid   要删除的黑名单用户id  black_user_id
     */
    public void deleteBlackList(long uid) {
        //获取当前登录用户id
        Long userId = UserHolder.getUserId();
        pageResultApi.deleteBlackList(uid,userId);
    }
}
